package com.tbvtc.agriculturalcreditchainserver2025.comment.Token;

import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JwtUtil {
    private static final String SECRET_KEY = "M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ"; // 生产环境建议使用复杂密钥
    private static final long EXPIRATION_TIME = 864000000L; // 24小时
//    private static final long EXPIRATION_TIME = 31536000000L; // 24小时
    public static String createToken(String phone, Long userId) {
        return Jwts.builder()
                .claim("phone", phone)    // 自定义声明
                .claim("userId", userId)  // 添加用户ID
                .setIssuedAt(new Date())  // 签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // 过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 签名算法
                .compact();
    }
     //解析tokne
    public static Claims parseToken(String token) {
        log.info("解析token");
        if (token == null){
            log.info("获取到jwt令牌为空, 返回错误结果");
            throw new FoodException(ResultCodeEnum.TOKEN_INVALID);
        }

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (ExpiredJwtException e) {
            throw new FoodException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (SignatureException e) {
            throw new FoodException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
    public static void main(String[] args) {
        String token = createToken("17612250408", 20L);
        System.out.println(token);
        Claims claims = parseToken(token);
        System.out.println(claims.get("phone", String.class));
    }
}




